package com.xbongbong.workflow.service.strategy.data.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xbongbong.i18n.util.I18nMessageUtil;
import com.xbongbong.paas.constant.PaasConstant;
import com.xbongbong.paas.domain.entity.PaasFormDataEntity;
import com.xbongbong.paas.elasticsearch.pojo.XbbAggregatedPage;
import com.xbongbong.paas.elasticsearch.util.EsUtil;
import com.xbongbong.paas.elasticsearch.util.XbbElasticsearchRestTemplate;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.enums.IndexTypeEnum;
import com.xbongbong.paas.enums.PlatFormEnum;
import com.xbongbong.paas.enums.TaskTypeEnum;
import com.xbongbong.paas.log.constant.CrmLogMemoConstant;
import com.xbongbong.paas.pojo.dto.SaasFormSaveDTO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.Arith;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.toolbox.util.CollectionsUtil;
import com.xbongbong.paas.toolbox.util.DateTimeUtil;
import com.xbongbong.paas.toolbox.util.StringUtil;
import com.xbongbong.paas.toolbox.wrap.UserVO;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.paas.util.FormDataUtil;
import com.xbongbong.pro.constant.I18nStringConstant;
import com.xbongbong.pro.customercommunicate.pojo.dto.CustomerDynamicAddDTO;
import com.xbongbong.pro.domain.entity.UpdateDataEntity;
import com.xbongbong.pro.enums.DistributorMarkEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.SaasNeedRedundantAttrPojo;
import com.xbongbong.pro.refund.pojo.vo.RefundRedContractVO;
import com.xbongbong.pro.workflow.enums.WorkflowOperateEnum;
import com.xbongbong.saas.constant.StringConstant;
import com.xbongbong.saas.domain.entity.ContractProductEntity;
import com.xbongbong.saas.domain.entity.OutstockProductEntity;
import com.xbongbong.saas.domain.entity.RefundUserEntity;
import com.xbongbong.saas.domain.entity.ext.ContractEntityExt;
import com.xbongbong.saas.domain.entity.ext.RefundEntityExt;
import com.xbongbong.saas.enums.ProjectLogEnum;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.ContractEnum;
import com.xbongbong.saas.enums.business.RefundEnum;
import com.xbongbong.saas.enums.dictionary.DictionaryEnum;
import com.xbongbong.saas.enums.product.ContractProductEnum;
import com.xbongbong.saas.enums.subform.ContractProductSubFormEnum;
import com.xbongbong.saas.help.RefundHelp;
import com.xbongbong.saas.model.ContractModel;
import com.xbongbong.saas.model.ContractProductModel;
import com.xbongbong.saas.model.DataDictionaryModel;
import com.xbongbong.saas.model.OutstockProductModel;
import com.xbongbong.saas.model.PaasFormSubDataModel;
import com.xbongbong.saas.model.RefundModel;
import com.xbongbong.saas.model.RefundUserModel;
import com.xbongbong.saas.service.CustomerCommunicateService;
import com.xbongbong.saas.toolbox.help.FastJsonHelper;
import com.xbongbong.sys.domain.entity.UserEntity;
import com.xbongbong.sys.model.UserModel;
import com.xbongbong.workflow.domain.entity.WorkflowBackupDataEntity;
import com.xbongbong.workflow.model.WorkflowBackupDataModel;
import com.xbongbong.workflow.pojo.Data;
import com.xbongbong.workflow.pojo.User;
import com.xbongbong.workflow.pojo.WorkflowTransferPOJO;
import com.xbongbong.workflow.service.strategy.data.AbstractWorkflowDataStrategy;
import com.xbongbong.workflow.service.strategy.data.WorkflowDataProcessStrategy;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleFromFormData;
import static com.xbongbong.saas.toolbox.help.FastJsonHelper.getDoubleOrDefaultFromFormData;
import static org.elasticsearch.index.query.QueryBuilders.boolQuery;
import static org.elasticsearch.index.query.QueryBuilders.termQuery;

/**
 *
 * @author 魏荣杰
 *
 */
@Service
@Slf4j
public class WorkflowRefundStrategy extends AbstractWorkflowDataStrategy implements WorkflowDataProcessStrategy {

    @Resource
    private ContractModel contractModel;
    @Resource
    private RefundModel refundModel;
    @Resource
    private UserModel userModel;
    @Resource
    private DataDictionaryModel dataDictionaryModel;
    @Resource
    private CustomerCommunicateService customerCommunicateService;
    @Resource
    private ContractProductModel contractProductModel;
    @Resource
    private OutstockProductModel outstockProductModel;
    @Resource
    private XbbElasticsearchRestTemplate xbbElasticsearchRestTemplate;
    @Resource
    private RefundHelp refundHelp;
    @Resource
    private WorkflowBackupDataModel workflowBackupDataModel;
    @Resource
    private RefundUserModel refundUserModel;
    @Resource
    private PaasFormSubDataModel paasFormSubDataModel;


    @Override
    public List<Integer> type() {
        return Collections.singletonList(XbbRefTypeEnum.REFUND.getCode());
    }

    @Override
    public void save(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {

        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);

        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();
        User user = workflowTransferPOJO.getUser();
        String creatorId = user.getUserId();
        UserEntity creatorUser = userModel.getByKeyIngoreDel(creatorId, corpid);


        RefundEntityExt newRefundEntityExt = refundModel.getByKey(dataId, corpid);
        newRefundEntityExt.setData(data);

        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID.getAttr(), 0L);

        Long contractId = FastJsonHelper.getLongOrDefaultFromFormData(data, RefundEnum.CONTRACT_ID.getAttr(), 0L);

        Double returnAmount = getDoubleOrDefaultFromFormData(data, RefundEnum.RETURN_AMOUNT.getAttr(), 0D);

        ContractEntityExt contractEntityExt = contractModel.getByKey(contractId, corpid);
        UserVO creatorUserVO = new UserVO();
        BeanUtil.copyProperties(creatorUser, creatorUserVO);
        RefundRedContractVO refundRedContractVO = refundHelp.generateRedContract(newRefundEntityExt, contractEntityExt, returnAmount, data.getJSONArray(RefundEnum.PRODUCTS.getAttr()), FlowStatusEnum.NOT_NEED_APPROVAL.getType(), true, creatorUserVO);
        ContractEntityExt redContractEntity = refundRedContractVO.getContractEntityExt();
        Long redContractId = redContractEntity.getId();


//        ReRollBackEntity reRollBackEntity = associatedBusinessAfterSavePojo.getReRollBackEntity();
        SaasFormSaveDTO saasFormSaveDTO = new SaasFormSaveDTO();
        saasFormSaveDTO.setCorpid(corpid);
        UserVO userVO = new UserVO();
        BeanUtil.copyProperties(creatorId, userVO);
        saasFormSaveDTO.setLoginUser(userVO);
        saasFormSaveDTO.setUserId(user.getUserId());
        saasFormSaveDTO.setLoginUserName(user.getName());
        saasFormSaveDTO.setNewPaasFormDataEntity(newRefundEntityExt);
        saasFormSaveDTO.setNewData(data);
        saasFormSaveDTO.setOldData(data);
        saasFormSaveDTO.setOldPaasFormDataEntity(newRefundEntityExt);
        List<Long> redPaymentSheetIds = new ArrayList<>();
        try {
            redPaymentSheetIds = refundHelp.generateRedPayment(redContractEntity, data.getJSONArray(RefundEnum.PAYMENT_SHEETS.getAttr()), saasFormSaveDTO);
        } catch (Exception e) {
            log.error("WorkflowRefundStrategy.save generateRedPayment：", e);
        }

//        reRollBackEntity.setRedSheetId(redPaymentSheetIds);
        List<Long> redPaymentIds = new ArrayList<>();
        try {
            redPaymentIds = refundHelp.generateRedPaymentPlan(redContractEntity, data.getJSONArray(RefundEnum.PAYMENTS.getAttr()), saasFormSaveDTO);
        } catch (Exception e) {
            log.error("WorkflowRefundStrategy.save generateRedPaymentPlan：", e);
        }
//        reRollBackEntity.setRedPaymentId(redPaymentIds);
        // --关联发票红冲/作废--*/
        List<Long> invoiceIds = new ArrayList<>();
        try {
            invoiceIds = refundHelp.saveRefundInvoice(saasFormSaveDTO, data.getJSONArray(RefundEnum.INVOICES.getAttr()), redContractId, FlowStatusEnum.NOT_NEED_APPROVAL.getType());
        } catch (Exception e) {
            log.error("WorkflowRefundStrategy.save saveRefundInvoice：", e);
        }
//        reRollBackEntity.setRedInvoiceId(invoiceIds);
        // 更新退货退款中关联发票和关联红冲回款单字段内容（红冲发票和红冲回款单属于新建，其id在新建成功后才能拿到）
        JSONObject updateRefundData = new JSONObject();
        if (!invoiceIds.isEmpty()) {
            data.put(RefundEnum.INVOICES.getAttr(), invoiceIds);
            updateRefundData.put(RefundEnum.INVOICES.getAttr(), invoiceIds);
        } else {
            data.put(RefundEnum.INVOICES.getAttr(), null);
            data.put(RefundEnum.INVOICES_LINKED_TEXT.getAttr(), null);
            updateRefundData.put(RefundEnum.INVOICES.getAttr(), null);
            updateRefundData.put(RefundEnum.INVOICES_LINKED_TEXT.getAttr(), null);
        }
        if (!redPaymentSheetIds.isEmpty()) {
            data.put(RefundEnum.PAYMENT_SHEETS.getAttr(), redPaymentSheetIds);
            updateRefundData.put(RefundEnum.PAYMENT_SHEETS.getAttr(), redPaymentSheetIds);
//            if (associatedBusinessAfterSavePojo.getRefundAmount() != null) {
//                data.put(RefundEnum.REFUND_AMOUNT.getAttr(), associatedBusinessAfterSavePojo.getRefundAmount());
//            }
            Double refundAmount = getDoubleOrDefaultFromFormData(data, RefundEnum.REFUND_AMOUNT.getAttr(), 0D);
            if (refundAmount != null) {
                data.put(RefundEnum.REFUND_AMOUNT.getAttr(), refundAmount);
                updateRefundData.put(RefundEnum.REFUND_AMOUNT.getAttr(), refundAmount);
            }
        } else {
            data.put(RefundEnum.PAYMENT_SHEETS.getAttr(), null);
            data.put(RefundEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), null);
            updateRefundData.put(RefundEnum.PAYMENT_SHEETS.getAttr(), null);
            updateRefundData.put(RefundEnum.PAYMENT_SHEETS_LINKED_TEXT.getAttr(), null);
        }
        //应收款无审批
        if (!redPaymentIds.isEmpty()) {
            data.put(RefundEnum.PAYMENTS.getAttr(), redPaymentIds);
            updateRefundData.put(RefundEnum.PAYMENTS.getAttr(), redPaymentIds);
        } else {
            data.put(RefundEnum.PAYMENTS.getAttr(), null);
            data.put(RefundEnum.PAYMENTS_LINKED_TEXT.getAttr(), null);
            updateRefundData.put(RefundEnum.PAYMENTS.getAttr(), null);
            updateRefundData.put(RefundEnum.PAYMENTS_LINKED_TEXT.getAttr(), null);
        }

        newRefundEntityExt.setData(data);
        List<UpdateDataEntity> list = new ArrayList<>();
        list.add(ExplainUtil.getUpdateData(newRefundEntityExt.getId(), updateRefundData, corpid));
        refundModel.updateBatch(list, corpid);

        // 项目日志
        try{
            String customerName = FastJsonHelper.getStringOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID_LINKED_TEXT.getAttr(), "");
            String refundReason = FastJsonHelper.getStringFromFormData(data, RefundEnum.REFUND_REASON.getAttr());
            boolean notDistributeBusinessType = isNotDistributeBusinessType(workflowTransferPOJO);
            CustomerDynamicAddDTO customerDynamicAddDTO = new CustomerDynamicAddDTO();
            String communicateMemo;
            if (notDistributeBusinessType) {
                 communicateMemo =String.format(I18nMessageUtil.getMessage(CrmLogMemoConstant.DYNAMIC_USER_ADD_REFUND), creatorUser.getName(), newRefundEntityExt.getSerialNo());
                if (!StringUtil.isEmpty(refundReason)) {
                    //获取启用的退货原因
                    Map<String, String> refundReasonMap = dataDictionaryModel.getDictionaryMap4Saas(DictionaryEnum.REFUND_REASON, corpid, newRefundEntityExt.getFormId());
                    String refundReasonStr = refundReasonMap.get(refundReason) == null ? "" : refundReasonMap.get(refundReason);
                    if (!StringUtil.isEmpty(refundReasonStr)) {
                        communicateMemo += "," + RefundEnum.REFUND_REASON.getAttrName() + "\"" + refundReasonStr + "\"";
                    }
                }
            }else {
                 communicateMemo = creatorUser.getName() + I18nMessageUtil.getMessage(I18nStringConstant.CREATE_REFUND);
                if (!StringUtil.isEmpty(refundReason)) {
                    //获取启用的退货原因
                    Map<String, String> refundReasonMap = dataDictionaryModel.getDictionaryMap4Saas(DictionaryEnum.REFUND_REASON, corpid, newRefundEntityExt.getFormId());
                    String refundReasonStr = refundReasonMap.get(refundReason) == null ? "" : refundReasonMap.get(refundReason);
                    if (!StringUtil.isEmpty(refundReasonStr)) {
                        communicateMemo += "，"+ RefundEnum.REFUND_REASON.getAttrName() +": " + refundReasonStr;
                    }
                }
                customerDynamicAddDTO.setDistributorMark(DistributorMarkEnum.DISTRIBUTOR.getCode());
            }

            customerDynamicAddDTO.setCorpid(corpid);
            customerDynamicAddDTO.setUserId(creatorId);
            customerDynamicAddDTO.setCustomerId(customerId);
            customerDynamicAddDTO.setContractIds(Collections.singletonList(contractId));
            customerDynamicAddDTO.setCustomerName(customerName);
            customerDynamicAddDTO.setMemo(communicateMemo);
            customerDynamicAddDTO.setCommunicateBusinessText(newRefundEntityExt.getSerialNo());
            customerDynamicAddDTO.setCommunicateBusinessType(XbbRefTypeEnum.REFUND.getCode());
            customerDynamicAddDTO.setDataId(dataId);
            customerDynamicAddDTO.setLogType(ProjectLogEnum.REFUND_CREATE.getSubType());
            customerDynamicAddDTO.setPlatform(PlatFormEnum.INTERNAL.getValue());
            customerCommunicateService.addCustomerDynamic(customerDynamicAddDTO);
        }catch (Exception e){
            log.error("资金创建项目日志", e);
        }
        // api
        apiHook(workflowTransferPOJO);
        addLinkDataDynamic(workflowTransferPOJO);
        // log
        afterSaveLog(workflowTransferPOJO);
    }

    @Override
    public void update(WorkflowTransferPOJO workflowTransferPOJO, SaasNeedRedundantAttrPojo saasNeedRedundantAttrPojo) throws XbbException {
        // 文件柜
        saveDataCabinetFile(workflowTransferPOJO);


        String corpid = workflowTransferPOJO.getCorpid();
        Data pojoData = workflowTransferPOJO.getData();
        JSONObject data = pojoData.getData();
        Long dataId = pojoData.getId();


        RefundEntityExt newRefundEntityExt = refundModel.getByKey(dataId, corpid);
        newRefundEntityExt.setData(data);

        Long customerId = FastJsonHelper.getLongOrDefaultFromFormData(data, RefundEnum.CUSTOMER_ID.getAttr(), 0L);

        Long contractId = FastJsonHelper.getLongOrDefaultFromFormData(data, RefundEnum.CONTRACT_ID.getAttr(), 0L);

        Double returnAmount = getDoubleOrDefaultFromFormData(data, RefundEnum.RETURN_AMOUNT.getAttr(), 0D);

        ContractEntityExt contractEntityExt = contractModel.getByKey(contractId, corpid);
        // 更新退货产品
        Map<Long, Double> changeNumMap = refundHelp.setRefundProducts(newRefundEntityExt);
        JSONArray jsonArray = newRefundEntityExt.getData().getJSONArray(RefundEnum.PRODUCTS.getAttr());
        List<Long> refList = new ArrayList<>();
        Map<Long, Double> refNumMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
        if (Objects.nonNull(jsonArray)) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                // 上游单据，原合同产品表ID
                Long refProductId = FastJsonHelper.getLongFromFormData(jsonObject, ContractProductSubFormEnum.REF_PRODUCT_ID.getDataAttr());
                if (Objects.nonNull(refProductId)) {
                    refList.add(refProductId);
                    refNumMap.put(refProductId, changeNumMap.getOrDefault(refProductId, getDoubleFromFormData(jsonObject, ContractProductEnum.NUM.getAttr())));
                }
            }
            // 原先的产品变化
            Iterator iterator = changeNumMap.keySet().iterator();
            while (iterator.hasNext()) {
                Long contractProductId = (Long)iterator.next();
                Double changeNum = changeNumMap.get(contractProductId);
                if(!refList.contains(contractProductId)){
                    refList.add(contractProductId);
                    refNumMap.put(contractProductId, changeNum);
                }
            }
        }
        if (!refList.isEmpty()) {
            boolean ifJXCOpen = refundHelp.ifJXCOpen(corpid);
            List<ContractProductEntity> contractProductEntityList = contractProductModel.getContractProductByContractIdIn(corpid, Collections.singletonList(contractId));

            if(ifJXCOpen){
                JSONObject contractData = contractEntityExt.getData();
                List<Long> outstockIds = FastJsonHelper.getJsonArrOrDefaultFromFormData(contractData, ContractEnum.OUTSTOCK_ID.getAttr(), new JSONArray()).toJavaList(Long.class);
                // 未出库就不执行
                if(!outstockIds.isEmpty()){
                    // 处理出库产品表和原合同产品表
                    Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    params.put("corpid", corpid);
                    params.put("outstockIdIn", outstockIds);
                    params.put("del", DelEnum.NORMAL.getDel());
                    List<OutstockProductEntity> outstockProductEntities = outstockProductModel.findEntitys(params);
                    Map<Long, Double> refNumsMap = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    for(OutstockProductEntity item : outstockProductEntities){
                        // 销售出库产品表，上游单据合同ID
                        if (refNumMap.containsKey(item.getId())) {
                            item.setInstockNum(Arith.add(item.getInstockNum() == null ? 0D : item.getInstockNum(), refNumMap.get(item.getId())));
                            refNumsMap.put(item.getRefProductId(), Arith.add(refNumMap.get(item.getId()),refNumsMap.getOrDefault(item.getRefProductId(), 0D)));
                        }
                    }
                    outstockProductModel.updateBatch(outstockProductEntities, corpid);
                    if (!refNumsMap.isEmpty()){
                        for (ContractProductEntity item : contractProductEntityList) {
                            Double instockNum = item.getInstockNum() == null ? 0D : item.getInstockNum();
                            if (refNumsMap.containsKey(item.getId())) {
                                item.setInstockNum(Arith.add(instockNum, refNumsMap.getOrDefault(item.getId(), 0D)));
                            }
                        }
                        contractProductModel.updateBatch(contractProductEntityList, corpid);
                    }
                }
            } else {
                // 处理原合同产品表
                    /*Map<String, Object> params = new HashMap<>(PaasConstant.DEFAULT_INITIAL_CAPACITY);
                    params.put("corpid", corpid);
                    params.put("idIn", refList);
                    params.put("del", DelEnum.NORMAL.getDel());
                    List<ContractProductEntity> contractProductEntities = contractProductModel.findEntitys(params);*/
                contractProductEntityList.forEach(item -> {
                    if (refNumMap.containsKey(item.getId())) {
                        item.setInstockNum(Arith.add(item.getInstockNum(), refNumMap.get(item.getId())));
                    }
                });
                contractProductModel.updateBatch(contractProductEntityList, corpid);
            }
        }

        Long redContractId = FastJsonHelper.getLongOrDefaultFromFormData(newRefundEntityExt.getData(), RefundEnum.RED_CONTRACT_ID.getAttr(), 0L);
        BoolQueryBuilder boolQueryBuilder = boolQuery();
        boolQueryBuilder.filter(termQuery("corpid.keyword", corpid));
        boolQueryBuilder.filter(termQuery(FieldTypeEnum.DATAID.getAlias(),redContractId));
        boolQueryBuilder.filter(termQuery("del", 0));
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(boolQueryBuilder);
        PageRequest pageRequest = EsUtil.setPage(sourceBuilder, 1, 1);
        SearchRequest searchRequest = new SearchRequest(IndexTypeEnum.IDX_SAAS_CONTRACT.getIndex());
        searchRequest.source(sourceBuilder);
        XbbAggregatedPage<ContractEntityExt> esEntities = xbbElasticsearchRestTemplate.queryForPages(pageRequest, searchRequest, ContractEntityExt.class);
        ContractEntityExt redContractEntity = new ContractEntityExt();
        for (PaasFormDataEntity entity : esEntities.getContent()) {
            BeanUtil.copyProperties(entity, redContractEntity);
        }
        // 更新红冲合同的合同成本，合同毛利，现金毛利(包含新建和编辑)
        refundHelp.updateRedContract(jsonArray, corpid, redContractEntity, contractEntityExt,newRefundEntityExt.getData(), returnAmount, false , newRefundEntityExt.getId());


        // api
        apiHook(workflowTransferPOJO);
        // log
        afterUpdateLog(workflowTransferPOJO);
    }

    @Override
    public void updateBack(Long taskId, WorkflowTransferPOJO workflowTransferPOJO) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Long backupDataId = workflowTransferPOJO.getBackupDataId();
            Long dataId = workflowTransferPOJO.getData().getId();
            WorkflowBackupDataEntity workflowBackupDataEntity = workflowBackupDataModel.getByKey(backupDataId, corpid);
            if (Objects.nonNull(workflowBackupDataEntity)) {
                JSONObject data = workflowBackupDataEntity.getData();

                replenishAttrForBackupData(workflowTransferPOJO.getData().getData(), data);

                RefundEntityExt refundEntityExt = new RefundEntityExt();
                refundEntityExt.setId(dataId);
                refundEntityExt.setCorpid(corpid);
                refundEntityExt.setData(data);
                refundEntityExt.setSerialNo(data.getString(FieldTypeEnum.SERIALNO.getAlias()));
                refundEntityExt.setOwnerId(getOwnerId(data));
                refundEntityExt.setDepartmentId(data.getLong(FieldTypeEnum.DEPARTMENTID.getAlias()));

                List<RefundUserEntity> refundUserEntityList = JSON.parseArray(data.getString(StringConstant.USER_TEAM), RefundUserEntity.class);

                FormDataUtil.removeSystemData(data);
                data.remove(StringConstant.USER_TEAM);
                if (Objects.equals(workflowTransferPOJO.getOperate(), WorkflowOperateEnum.UPDATE.getType())) {
                    refundEntityExt.setFlowStatus(FlowStatusEnum.PASS.getType());
                }
                refundModel.update(refundEntityExt);

                // 回退被删掉的子表单
                updateBackSubForm(refundEntityExt, corpid, IndexTypeEnum.IDX_SAAS_REFUND_SUB);
                //回退被删掉的富文本
                updateBackRichText(taskId, workflowTransferPOJO);
                // 团队保存
                saveUserTeam(refundUserEntityList, corpid, refundEntityExt.getId());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowRefundStrategy.updateBack error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    @Override
    public void approvalFailed(Long taskId, WorkflowTransferPOJO workflowTransferPOJO, Integer taskType) throws XbbException {
        try {
            String corpid = workflowTransferPOJO.getCorpid();
            Data workflowData = workflowTransferPOJO.getData();
            Long dataId = workflowData.getId();
            Long formId = workflowData.getFormId();
            Integer businessType = workflowData.getBusinessType();
            Integer saasMark = workflowData.getSaasMark();
            RefundEntityExt refundEntityExt = new RefundEntityExt();
            refundEntityExt.setId(dataId);
            if (Objects.equals(TaskTypeEnum.REVOKE.getType(), taskType)) {
                refundEntityExt.setFlowStatus(FlowStatusEnum.REVOKE.getType());
            } else {
                refundEntityExt.setFlowStatus(FlowStatusEnum.REJECT.getType());
            }
            refundEntityExt.setCorpid(corpid);
            refundEntityExt.setUpdateTime(DateTimeUtil.getInt());
            refundModel.update(refundEntityExt);
            // 子表单
            DelEnum del = DelEnum.APPROVE_FAILED;

            paasFormSubDataModel.deleteBatchByDataId(Collections.singletonList(dataId), corpid, IndexTypeEnum.IDX_SAAS_REFUND_SUB, del);
            //富文本
            deleteFormRichText(dataId, corpid, formId, businessType, saasMark, DelEnum.NORMAL);


            // 团队
            List<RefundUserEntity> contractUserList = refundUserModel.getByRefundId(corpid, dataId);
            if (CollectionsUtil.isNotEmpty(contractUserList)) {
                refundUserModel.deleteBatchUser(contractUserList, corpid, del.getDel());
            }
        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowRefundStrategy.approvalFailed error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }

    private void saveUserTeam(List<RefundUserEntity> refundUserEntityList, String corpid, Long id) throws XbbException {
        try {
            List<Long> ids = new ArrayList<>();
            refundUserEntityList.forEach(v -> ids.add(v.getId()));

            List<RefundUserEntity> userEntities = refundUserModel.getByRefundId(corpid, id);
            List<RefundUserEntity> refundUserEntities = userEntities.stream().filter(v -> !ids.contains(v.getId())).collect(Collectors.toList());

            refundUserModel.deleteBatchUser(refundUserEntities, corpid, DelEnum.DELETE.getDel());

            refundUserModel.updateBatch(refundUserEntityList, corpid);

        } catch (Exception e) {
            log.error("com.xbongbong.workflow.service.strategy.data.impl.WorkflowRefundStrategy.saveUserTeam error", e);
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001);
        }
    }
}
